﻿using System.Net;
using System.Text;

namespace MooToolWPF.Utility.Encode;

public static class UrlEncodeHelper
{
    /// <summary>
    /// 默认方式-基于utf8
    /// </summary>
    /// <param name="src"></param>
    /// <returns></returns>
    public static string UrlEncode(string src)
    {
        var urlEncode = WebUtility.UrlEncode(src);
        return urlEncode;
    }


    /// <summary>
    /// 
    /// </summary>
    /// <param name="src"></param>
    /// <returns></returns>
    public static string UrlDecode(string src)
    {
        var urlDecode = WebUtility.UrlDecode(src);
        return urlDecode;
    }

    /// <summary>
    /// 编码-基于gb2312
    /// </summary>
    /// <param name="str"></param>
    /// <param name="encoding"></param>
    /// <returns></returns>
    public static string UrlEncode(string str, Encoding encoding)
    {
        StringBuilder sb = new StringBuilder();
        byte[] bytes = encoding.GetBytes(str);
        foreach (byte b in bytes)
        {
            // 保留字母、数字和一些未保留的字符
            if (
                (b >= 'A' && b <= 'Z') ||
                (b >= 'a' && b <= 'z') ||
                (b >= '0' && b <= '9') ||
                b == '-' || b == '_' || b == '.' || b == '~'
            )
            {
                sb.Append((char)b);
            }
            else
            {
                sb.Append('%' + $"{b:X2}");
            }
        }
        return sb.ToString();
    }


    /// <summary>
    /// 解码-基于gb2312
    /// </summary>
    /// <param name="str"></param>
    /// <param name="encoding"></param>
    /// <returns></returns>
    public static string UrlDecode(string str, Encoding encoding)
    {
        Byte[] bytes = new Byte[str.Length];
        int count = 0;

        for (int i = 0; i < str.Length; i++)
        {
            if (str[i] == '%')
            {
                if (i + 2 < str.Length)
                {
                    var hex = str.Substring(i + 1, 2);
                    bytes[count++] = Convert.ToByte(hex, 16);
                    i += 2;
                }
            }
            else if (str[i] == '+')
            {
                bytes[count++] = (byte)' ';
            }
            else
            {
                bytes[count++] = (byte)str[i];
            }
        }

        return encoding.GetString(bytes, 0, count);
    }
}